/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package autodispose;

import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.functions.Consumer;

/**
 * Utilities for dealing with AutoDispose scopes.
 *
 * @author rWX1019951
 */
public final class Scopes {
    /**
     * Private constructor
     */
    private Scopes() {
    }

    /**
     * Static method to handle {@link OutsideScopeException OutsideScopeExceptions}.
     *
     * @param scopeProvider .
     * @return {@link Completable} representation of the given {@code scopeProvider}.
     * This will be deferred appropriately and handle {@link OutsideScopeException OutsideScopeExceptions}.
     */
    public static Completable completableOf(ScopeProvider scopeProvider) {
        return Completable.defer(() -> {
            try {
                return scopeProvider.requestScope();
            } catch (OutsideScopeException e) {
                Consumer<? super OutsideScopeException> handler = AutoDisposePlugins.getOutsideScopeHandler();
                if (handler != null) {
                    handler.accept(e);
                    return Completable.complete();
                } else {
                    return Completable.error(e);
                }
            }
        });
    }
}
